package com.libservice.activityservice

import android.app.Activity
import android.app.Application
import android.os.Build
import android.os.Bundle

class ActivityService(application: Application) : ActivityServiceInterface {
    private val _activities: ArrayList<Activity> = arrayListOf()

    override val activities: List<Activity>
        get() = _activities

    override val currentActivity: Activity?
        get() = _activities.lastOrNull()

    override val firstActivity: Activity?
        get() = _activities.firstOrNull()

    init {
        application.registerActivityLifecycleCallbacks(object :
            Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
                _activities.add(activity)
            }

            override fun onActivityStarted(activity: Activity) {
            }

            override fun onActivityResumed(activity: Activity) {
            }

            override fun onActivityPaused(activity: Activity) {
            }

            override fun onActivityStopped(activity: Activity) {
            }

            override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {
            }

            override fun onActivityDestroyed(activity: Activity) {
                _activities.remove(activity)
            }
        })
    }

    override fun pop(animated: Boolean) {
        currentActivity?.let {
            it.finish()

            if (!animated) {
                if (Build.VERSION.SDK_INT >= 34) {
                    it.overrideActivityTransition(Activity.OVERRIDE_TRANSITION_CLOSE, 0, 0)
                } else {
                    @Suppress("DEPRECATION")
                    it.overridePendingTransition(0, 0)
                }
            }
        }
    }

    override fun popToActivity(activity: Activity, animated: Boolean) {
        if (_activities.indexOf(activity) == -1) {
            return
        }

        while (_activities.last() != activity) {
            _activities.removeLast().apply {
                finish()
                if (!animated) {
                    if (Build.VERSION.SDK_INT >= 34) {
                        overrideActivityTransition(Activity.OVERRIDE_TRANSITION_CLOSE, 0, 0)
                    } else {
                        @Suppress("DEPRECATION")
                        overridePendingTransition(0, 0)
                    }
                }
            }
        }
    }

    override fun popToRootActivity() {
        while (_activities.size > 1) {
            _activities.removeLast().finish()
        }
    }
}